<?php

namespace app\wechat\controller\account;

use app\admin\controller\Base;
use app\admin\model\Authorizer;
use think\facade\Env;
use think\facade\Cache;
use think\facade\Log;
use think\Db;
use DOMDocument;
use CURLFile;

// 第三方平台
class Prowechat extends Base
{

    public $component_appid; //第三方平台appid
    public $component_appsecret; //第三方平台appsecret

    public function __construct()
    {
        $this->component_appid     = Env::get('open_platform.WECHAT_OPEN_PLATFORM_APPID');
        $this->component_appsecret = Env::get('open_platform.WECHAT_OPEN_PLATFORM_SECRET');
    }
    /**
     * 获取第三方平台的component_verify_ticket
     * 将获取到的ticket保存着在 nx_system的表中
    **/
    public function getComponentVerifyTicket()
    {
        $timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']);
        $nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']);
        $msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']);
        $encryptMsg = file_get_contents('php://input');
        $pc = new wxBizMsg();
        $xml_tree = new DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
        $msg = '';
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        if ($errCode == 0) {
            $xml = new DOMDocument();
            $xml->loadXML($msg);
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
            $component_verify_ticket = $array_e->item(0)->nodeValue;
            DB::name('nx_system')->where(['delstatus' => 1, 'title' => 'wechat_verifyticket'])
                ->update(['title' => 'wechat_verifyticket', 'content' => $component_verify_ticket, 'updatetime' => date('Y-m-d H:i:s', time())]);
            echo 'success';
        } else {
            DB::name('nx_system')->where(['delstatus' => 1, 'title' => 'errorcode'])
                ->update(['title' => 'errorcode', 'content' => $errCode, 'updatetime' => date('Y-m-d H:i:s', time())]);
            Log::record($errCode);
        }
    }
    /**
     * 获取第三方平台的AccessToken
     * component_appid  第三方平台appid
     * component_appsecret  第三方平台appsecret
     * component_verify_ticket 保存在数据库中的tiket
     * $result 为返回结果
     **/
    public function getComponentAccessToken($appId,$appsecret)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
        $list = Db::table('nx_system')->where(['title' => 'wechat_verifyticket', 'delstatus' => 1])->field('content')->find();
        $tricket   = $list['content'];
        $data = '{"component_appid":"'.$appId .'","component_appsecret": "'.$appsecret.'","component_verify_ticket":"'.$tricket.'"}';
        $res = $this->http_post($url, $data);
        if ($res) {
            $result = json_decode($res, true);
            return $result;
        }
    }
    /**
     * 获取第三方平台的预授权码
     * component_appid  第三方平台appid
     * $token  第三方平台的component_access_token;
     * $result 为返回结果
     **/
    public function getPreAuthCode()
    {
        $token = Cache::get('componenttoken');
        if($token == false){
            Cache::rm('componenttoken');
            $info = $this->getComponentAccessToken($this->component_appid,$this->component_appsecret);
            $token = $info['component_access_token'];
            Cache::set('componenttoken',$token,'6800');
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$token;
        $data = '{"component_appid":"'.$this->component_appid.'"}';
        $result = $this->http_post($url,$data);
        return $result;
    }
    /**
     * 获取第三方平台的授权链接
     * component_appid  第三方平台appid
     * pre_auth_code  预授权码
     * $result 为返回结果
     **/
    public function getPreAuthUrl()
    {
        $precode = $this->getPreAuthCode();
        $arr = json_decode($precode,true);
        $code = $arr['pre_auth_code'];
        $uri  = 'http://wechat.nanxuncn.cn/wechat/index/callback';
        $url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$this->component_appid.'&pre_auth_code='.$code.'&redirect_uri='.$uri;
        return $url;
    }
    /**
     * 获取第三方平台的绑定公众号的令牌
     * ghid  公众号原始ID
     * component_appid  第三方平台appid·
     * authorizer_refresh_token  公众号刷新令牌
     * $result 为返回结果
     **/
    public function getAuthAccesTtoken($ghid)
    {
        $token = Cache::get('componenttoken');
        if($token == false){
            Cache::rm('componenttoken');
            $info = $this->getComponentAccessToken($this->component_appid,$this->component_appsecret);
            $token = $info['component_access_token'];
            Cache::set('componenttoken',$token,'6800');
        }
        $url  = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$token;
        $info = Authorizer::where('ghid',$ghid)->field('refresh_token,appid')->find();
        $data ='{
                "component_appid":"'.$this->component_appid.'",
                "authorizer_appid":"'.$info['appid'].'",
                "authorizer_refresh_token":"'.$info['refresh_token'].'",
                }';
        $res = $this->http_post($url,$data);
        return $res;
    }
    /**
     * 公众号上传图文消息内的图片获取URL
     * CURLFile 图片路径的处理
     * $result 为返回结果
     **/
    public function getImageUrl($ghid,$imgurl)
    {
        $token = Cache::get('access_token'.$ghid);
        if($token == false){
            $info = $this->getAuthAccesTtoken($ghid);
            $arr = json_decode($info,true);
            $token = $arr['authorizer_access_token'];
            Cache::set('access_token'.$ghid,$token,'6800');
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token='.$token.'&type=image';
        $root = Env::get('root_path');
        $rootpath = $root.'public';
        $abpath = str_replace('http://wechat.nanxuncn.cn',$rootpath,$imgurl);
        if (class_exists('\CURLFile')) {
            $data['media'] = new \CURLFile(realpath($abpath));
        } else {
            $data['media'] = '@'.realpath($abpath);
        }
        $result = $this->http_post($url,$data);
        return $result;
    }
    /**
     * 公众号新增其他类型永久素材
     * CURLFile 图片路径的处理
     * $result 为返回结果
     **/
    public function addOtherMaterial($ghid,$imgurl)
    {
        $token = Cache::get('access_token'.$ghid);
        if($token == false){
            $info = $this->getAuthAccesTtoken($ghid);
            $arr = json_decode($info,true);
            $token = $arr['authorizer_access_token'];
            Cache::set('access_token'.$ghid,$token,'6800');
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.$token.'&type=thumb';
        $root = Env::get('root_path');
        $rootpath = $root.'public';
        $abpath = str_replace('http://wechat.nanxuncn.cn',$rootpath,$imgurl);
        if (class_exists('\CURLFile')) {
            $data['media'] = new \CURLFile(realpath($abpath));
        } else {
            $data['media'] = '@'.realpath($abpath);
        }
        $result = $this->http_post($url,$data);
        return $result;
    }
    /**
     * 公众号新增永久图文素材
     * $result 为返回结果
     * thumb_media_id为新增其他类型永久素材后返回的media_id
     **/
    public function addForeverArticles($ghid)
    {
        $token = Cache::get('access_token'.$ghid);
        if($token == false){
            $info = $this->getAuthAccesTtoken($ghid);
            $arr = json_decode($info,true);
            $token = $arr['authorizer_access_token'];
            Cache::set('access_token'.$ghid,$token,'6800');
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token='.$token;
        $data = '{
            "articles": [{
            "title": TITLE,
            "thumb_media_id": THUMB_MEDIA_ID,
            "author": AUTHOR,
            "digest": DIGEST,
            "show_cover_pic": SHOW_COVER_PIC(0 / 1),
            "content": CONTENT,
            "content_source_url": CONTENT_SOURCE_URL,
            "need_open_comment":1,
            "only_fans_can_comment":1
            }]
        }';
        $result = $this->http_post($url,$data);
        return $result;
    }
}
